package auth

import (
	"gindemo/config"
	"net/http"

	"gindemo/pkg/jwt"
	"gindemo/pkg/logger"

	"github.com/gin-gonic/gin"
)

type UserInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// 登录controller
func LoginController(r *gin.Context) {
	respData := config.NewRespData()
	userinfo := UserInfo{}
	if err := r.ShouldBindJSON(&userinfo); err != nil {
		respData.Status = http.StatusUnauthorized
		respData.Message = err.Error()
		r.JSON(http.StatusOK, respData)
		return
	}
	// debug绑定日志
	logger.Debug(map[string]interface{}{"用户名": userinfo.Username, "密码": userinfo.Password}, "开始验证登录信息")
	if userinfo.Username == config.Username && userinfo.Password == config.Password {
		// 使用前段传过来的用户名作为jwt key 生成token
		ss, err := jwt.GenToken(userinfo.Username)
		if err != nil {
			logger.Error(map[string]interface{}{"用户名": userinfo.Username, "错误信息": err.Error()}, "token生成失败")
			respData.Status = http.StatusUnauthorized
			respData.Message = "token生成失败"
			r.JSON(http.StatusOK, respData)
			return
		}
		logger.Info(map[string]interface{}{"用户名": userinfo.Username}, "登录成功")
		data := make(map[string]interface{})
		data["token"] = ss
		respData.Status = http.StatusOK
		respData.Message = "登录成功"
		respData.Data = data
		r.JSON(http.StatusOK, respData)
		return
	} else {
		respData.Status = http.StatusUnauthorized
		respData.Message = "登录失败，用户名密码错误"
		r.JSON(http.StatusOK, respData)
		return
	}
}

// 注销controller
func LogoutController(r *gin.Context) {
	respData := config.NewRespData()
	respData.Status = http.StatusOK
	respData.Message = "注销成功"
	r.JSON(http.StatusOK, respData)
	logger.Debug(nil, "用户注销成功")
}
